import { reactive, ref, createApp, h } from 'vue'
import { ElDialog, ElButton } from 'element-plus'
import { loadPlugins } from '@/plugins/util/common'
import { directives } from '@/plugins/directive'
export class BaseTableComponent {
  tableLoading = ref(true)
  tableData = ref([])
  pageReq = {
    pageNo: 1,
    pageSize: 10,
  }
  dataPagination = ref({
    total: 0,
  })
  private tableReqDto = {
    pageNo: 1,
    pageSize: 10,
  }

  private reqFun = (reqDto: any): ApiPromise<any> => {
    console.log(reqDto)
    return {} as ApiPromise<any>
  }

  private renderBefore: ((res: any) => void) | undefined = (res: any) => {
    console.log(res)
  }
  constructor() {}

  private setTableLoading(loading: boolean) {
    this.tableLoading.value = loading
  }
  setTableDate(data: any) {
    this.tableData.value = data
  }

  setReqFun(reqFun: any) {
    this.reqFun = reqFun
  }

  setResponseDate(data: any) {
    this.setTableDate(data.content)
    this.dataPagination.value = data
    this.setTableLoading(false)
  }

  setReqDto(reqDto: any) {
    this.tableReqDto = reqDto
  }

  init(reqDto: any, reqFun: any, renderBefore?: (res: any) => void) {
    this.setReqDto(reqDto)
    this.setReqFun(reqFun)
    this.renderBefore = renderBefore
  }

  exeRequest = () => {
    this.setTableLoading(true)
    console.log(this.tableReqDto)
    console.log(this.tableReqDto)
    this.reqFun(this.tableReqDto).then((res) => {
      if (this.renderBefore) {
        this.renderBefore(res)
      }
      this.setResponseDate(res.data)
    })
  }

  onSearch = () => {
    this.tableReqDto.pageNo = 1
    this.exeRequest()
  }

  onPaginationChange = (pageNo: number, pageSize: number) => {
    this.tableReqDto.pageNo = pageNo
    this.tableReqDto.pageSize = pageSize
    this.exeRequest()
  }
}

export const useDefineTable = function (table: DefineTable) {
  const baseTableInstance = new BaseTableComponent()
  table.tableReqDto = { ...table.tableReqDto, ...baseTableInstance.pageReq }
  baseTableInstance.init(table.tableReqDto, table.request, table.renderBefore)
  baseTableInstance.exeRequest()
  return reactive({ ...baseTableInstance, ...table })
}
/**
 * 封装打开对话框的函数
 * @param {Object} options - 对话框配置选项
 * @param {string} [options.title='提示'] - 对话框标题
 * @param {Object} options.component - 要显示在对话框中的组件
 * @param {string} [options.width='50%'] - 对话框宽度
 * @param {Function} [options.onConfirm] - 点击确定按钮的回调函数
 * @param {Function} [options.onClose] - 对话框关闭的回调函数
 * @returns {Object} - 包含 open 和 close 方法的对象
 */
export const useDefineDialog = function (options: DialogOptions) {
  const { title = '提示', component, width = '50%', onConfirm, onClose } = options

  const dialogVisible = ref(false)
  const componentRef = ref()
  const confirmLoading = ref(false)
  const confirmDisabled = ref(false)

  const dialogComponent = () => {
    return {
      setup() {
        const handleConfirm = async () => {
          if (typeof onConfirm === 'function') {
            confirmLoading.value = true
            try {
              await componentRef.value?.onConfirm()
              onConfirm()
              dialogVisible.value = false
            } catch (e) {
            } finally {
              confirmLoading.value = false
            }
          }
        }

        const handleClose = () => {
          if (typeof onClose === 'function') {
            onClose()
          }
          dialogVisible.value = false
        }

        const handleOpened = async () => {
          try {
            confirmDisabled.value = true
            await componentRef.value?.onOpened()
          } catch (e) {} finally {
            confirmDisabled.value = false
          }
        }
        const handleOpen = () => {
          try {
            componentRef.value?.onOpen()
          } catch (e) {}
        }

        return () =>
          h(
            ElDialog,
            {
              modelValue: dialogVisible.value,
              'onUpdate:modelValue': (val) => (dialogVisible.value = val),
              closeOnClickModal: false,
              title,
              width,
              // onClose: handleClose,
              // onClosed: handleClosed,
              onOpen: handleOpen,
              onOpened: handleOpened,
              ...options.props,
            },
            {
              default: () => {
                // 检查传入的 content 是否为有效的组件
                if (typeof component === 'object' && component.instance?.setup) {
                  return h(component.instance, { ref: componentRef, ...component.attrs })
                } else {
                  console.error('传入的内容不是有效的 Vue 组件')
                  return null
                }
              },
              footer: () => [
                h(ElButton, { onClick: handleClose }, '取消'),
                h(ElButton, { onClick: handleConfirm, type: 'primary', loading: confirmLoading.value, disabled: confirmDisabled.value }, '确定'),
              ],
            }
          )
      },
    }
  }
  const dialogApp = createApp(dialogComponent())
  loadPlugins(dialogApp)
  directives(dialogApp)
  let mountNode: Element
  const open = (attr: any | undefined = {}) => {
    mountNode = document.createElement('div')
    if (attr) {
      component.attrs = { ...component.attrs, ...attr }
    }
    document.body.appendChild(mountNode)
    dialogApp.mount(mountNode)
    dialogVisible.value = true
  }
  const unmount = () => {
    dialogApp.unmount()
    document.body.removeChild(mountNode)
  }
  return {
    open,
    unmount,
    componentRef,
  }
}
